import 'package:flutter/cupertino.dart';
import '../../../core/network/request.dart';
import '../../../core/socket/socket_events.dart';
import '../../../core/socket/socket_service.dart';
import '../../../model/home/chat/chat_model.dart';

class ChatViewModel extends ChangeNotifier {
  // 单例 SocketService 实例
  final SocketService socketService = SocketService();

  final RequestService _request = RequestService();

  MessageListModel? _messageList;
  MessageListModel? get messageList => _messageList;

  /// UI层回调，收到新消息或数据更新时通知界面滚动到底部
  VoidCallback? onNewMessageReceived;

  ChatViewModel() {
    // 只注册一次监听，避免重复监听导致多次回调
    socketService.typed.onSendMessage((data) {
      onReceiveMessage(data);
    });
  }

  /// 处理接收到的消息，更新消息列表并通知UI
  void onReceiveMessage(SendMessagePayload data) {
    final newMsg = MessageModel(
      content: data.content,
      messageType: MessageType.text,
      sendTime: DateTime.now(),
      isMe: false,
    );
    _messageList?.messageList.insert(0, newMsg);
    notifyListeners();

    // 通知UI滚动到底部
    onNewMessageReceived?.call();
  }

  /// 初始化聊天列表数据
  Future<void> initChat(String imId) async {
    final response = await _request.get(
      '/friend/search/chat',
      queryParameters: {"im_id": imId},
    );
    _messageList = MessageListModel.fromJson(response.data);
    notifyListeners();

    // 数据加载完成，通知UI滚动到底部
    onNewMessageReceived?.call();
  }

  /// 发送消息，更新本地消息列表并通过 Socket 发送
  void sendMessage({required String message, required String imId}) {
    final newMsg = MessageModel(
      content: message,
      messageType: MessageType.text,
      sendTime: DateTime.now(),
      isMe: true,
    );
    _messageList?.messageList.insert(0, newMsg);
    notifyListeners();

    socketService.typed.emitSendMessage(SendMessagePayload(
      content: message,
      toImId: imId,
      roomId: null,
      messageType: MessageType.text,
    ));

    // 发送后通知UI滚动到底部
    onNewMessageReceived?.call();
  }

  @override
  void dispose() {
    // 解绑监听，避免内存泄漏
    socketService.typed.off(SocketEvent.sendMessage);
    super.dispose();
  }
}
